package com.ning.activitys.skysound.base;


import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;

import com.ning.activitys.skysound.datas.Constant;
import com.ning.activitys.skysound.service.PlayService;


/**
 * Created by dllo on 16/1/8.
 */
public abstract class BaseActivity extends AppCompatActivity{

    private boolean isBind = false;

    //以前通过Bind 对象,现在通过Service 对象
    public PlayService playService;
    private PlayService.PlayBind playBind;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //requestWindowFeature(Window.FEATURE_NO_TITLE);
        //将当前的Activity 加到Activity 集合里
        MyApplication.addActivity(this);

    }


    //PlayService服务
    private ServiceConnection connection = new ServiceConnection() {
        //绑定服务
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            playBind = (PlayService.PlayBind) service;
            //获得PlayService 对象
            playService = playBind.getPlayService();

     //设置接口对对象
            playService.setMusicUpDataListener(musicUpDataListener);

            musicUpDataListener.onChange(playService.getCurrentPlayPosition());

            isBind = true;

        }
        //断开服务
        @Override
        public void onServiceDisconnected(ComponentName name) {
            playService = null;
            isBind = false;
        }
    };



    //PlayService 里的更新的接口
    private PlayService.MusicUpDataListener musicUpDataListener = new PlayService.MusicUpDataListener() {
        @Override
        public void onPublish(int progress) {
            publish(progress);
        }

        @Override
        public void onChange(int position) {
            change(position);
        }
    };
    public abstract void publish(int progress);
    public abstract void change(int position);


    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyApplication.removeActivity(this);
    }

    //绑定服务的方法
    public void bindPlayService(){
        if (!isBind) {
            Intent intent = new Intent(this, PlayService.class);
            bindService(intent, connection, Context.BIND_AUTO_CREATE);
            isBind = true;
        }
    }
    //解绑服务的方法
    public void unBindPlayService(){
        if (isBind) {
            unbindService(connection);
            isBind = false;
        }
    }

}
